package com.heba.fragment.scan;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.feature.ItemFeatureUserObject;
import com.heba.bean.user.UserObject;
import com.heba.config.CommonConfig;
import com.heba.fragment.LazyFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.businesslist.BusinessHomePageActivity;
import com.heba.greenmulu.businesslist.BusinessPersonActivity;
import com.heba.greenmulu.diary.ItemPersonHomePageActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jason on 2020/9/17.
 */
public class FeatureUserFragment extends LazyFragment {

    private TextView tvFollowing;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;

    private String featureID;

    private List<ItemFeatureUserObject> featureUserObjectList;

    /**
     * 实例化fragment
     * 接收参数
     *
     * @param featureID
     * @return
     */
    public static FeatureUserFragment newInstance(String featureID) {
        FeatureUserFragment fragment = new FeatureUserFragment();
        Bundle bundle = new Bundle();
        bundle.putString(CommonConfig.FEATURE_ID, featureID);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 取出参数
     */
    private void parseArgument() {
        Bundle bundle = getArguments();
        featureID = bundle.getString(CommonConfig.FEATURE_ID, "");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_feature_user_recyclerview, container, false);
        parseArgument();
        initView(view);
        return view;
    }

    @Override
    protected void lazyLoad() {
        getUserListData();
    }

    private void initView(View view) {
        tvFollowing = view.findViewById(R.id.tv_following);
        recyclerView = view.findViewById(R.id.recyclerView);

        tvFollowing.setText(getResources().getString(R.string.mine_tab_follows));
        tvFollowing.setSelected(true);

        featureUserObjectList = new ArrayList<>();

        recycleAdapter = new QuickAdapter<ItemFeatureUserObject>(featureUserObjectList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.recycle_item_feature_user;
            }

            @Override
            public void convert(VH holder, ItemFeatureUserObject data, int position) {
                TextView tvTitle = holder.getView(R.id.tv_title);
                LinearLayout linearView = holder.getView(R.id.ll_view);

                tvTitle.setVisibility(View.GONE);
                tvTitle.setText(data.getTitle());
                if (data.getList() != null && !data.getList().isEmpty()) {
                    tvTitle.setVisibility(View.VISIBLE);
                    updateUser(linearView, data.getList());
                }
            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);
    }

    private void updateUser(LinearLayout linearLayout, List<UserObject> userObjects) {
        linearLayout.removeAllViews();
        for (int i = 0; i < userObjects.size(); i++) {
            View view = updateUserRowView(userObjects.get(i));
            linearLayout.addView(view);
        }
    }

    private View updateUserRowView(UserObject object) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.item_account_row, null);
        ImageView ivAvatar = view.findViewById(R.id.img_avatar);
        TextView tvName = view.findViewById(R.id.txt_name);
        TextView tvDesc = view.findViewById(R.id.txt_desc);
        TextView tv_follow = view.findViewById(R.id.txt_follow);
        tv_follow.setVisibility(View.VISIBLE);
        tvName.setText(object.getAccount());
        tvDesc.setText(object.getNickname());
        GlideUtil.loadImageWithPlaceHolderID(getContext(), object.getIcon(), ivAvatar, R.drawable.icon_head_portrait);

        //是否关注
        if (object.isFollow()) {
            //已关注
            tv_follow.setEnabled(false);
            tv_follow.setCompoundDrawables(null, null, null, null);
            tv_follow.setText(getContext().getResources().getString(R.string.mine_focus2));
        } else {
            //未关注
            tv_follow.setEnabled(true);
            Drawable left = getResources().getDrawable(R.drawable.icon_diary_focus_on, null);
            left.setBounds(0, 0, left.getMinimumWidth(), left.getMinimumHeight());
            tv_follow.setCompoundDrawablePadding(DensityUtils.dip2px(getActivity(), 4));
            tv_follow.setCompoundDrawables(left, null, null, null);
            tv_follow.setText(getContext().getResources().getString(R.string.mine_focus));
        }

        /**
         * 关注用户
         */
        tv_follow.setOnClickListener(v -> {
            loading.Start();
            new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                @Override
                public void Success() {
                    loading.End();
                    getUserListData();
                }

                @Override
                public void Fail(String error) {
                    loading.End();
                }
            }).followUser(getContext(), object.getUserID());
        });

        view.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString(CommonConfig.SEND_USER_ID, object.getUserID());
            if (object.getAccountType() == 0 ){
                openActivity(ItemPersonHomePageActivity.class, bundle);
            }else{
                openActivity(BusinessPersonActivity.class,bundle);
            }
        });
        return view;
    }

    /**
     * 获取关注特点用户列表
     */
    private void getUserListData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("FeatureID", featureID);
        client.get(Cfg.BaseUrl + "/Feature/mb_GetUsersFollowFeature", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getContext()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        if (!featureUserObjectList.isEmpty()) {
                            featureUserObjectList.clear();
                        }
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemFeatureUserObject> list = new Gson().fromJson(array.toString(), new TypeToken<List<ItemFeatureUserObject>>() {
                                }.getType());
                                featureUserObjectList.addAll(list);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if (null != featureUserObjectList && !featureUserObjectList.isEmpty()) {
                            recycleAdapter.notifyDataSetChanged();
                        }

                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }
}
